package com.example.zhxy.controller;

import com.example.zhxy.config.CreateVerifiCodeImage;
import com.example.zhxy.config.JwtHelper;
import com.example.zhxy.config.Result;
import com.example.zhxy.config.ResultCodeEnum;
import com.example.zhxy.model.Admin;
import com.example.zhxy.model.LoginFrom;
import com.example.zhxy.service.AdminService;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * ClassName: SystemConreller
 * Package: com.example.zhxy.controller
 * Description:
 * User: fzykd
 *
 * @Author: LQH
 * Date: 2023-02-13
 * Time: 15:03
 */
@RestController
@RequestMapping("/sms/system")
public class SystemController {

    @Autowired
    private AdminService adminService;


    //GET
    //	http://localhost:9001/sms/system/getInfo
    // 登录成功之后的页面跳转
    @GetMapping("/getInfo")
    public Result getInfo(@RequestHeader("token") String token){
        //获取的是请求头 中的 token 用的注解是 RequestHeader

        //验证token 是否国企
        boolean expiration = JwtHelper.isExpiration(token);

        if (expiration){
            return Result.build(null,ResultCodeEnum.TOKEN_ERROR);
        }
        // 如果没过期 那么解析用户名 id 和 用户类型
        Long userId = JwtHelper.getUserId(token);
        Integer userType = JwtHelper.getUserType(token);

        //准备map集合 返回数据
        Map<String,Object> map = new LinkedHashMap<>();


        switch (userType){
            case 1:
                Admin admin = adminService.getAdminById(userId);
                map.put("userType",1);
                map.put("user",admin);
                break;
        }


        return Result.ok(map);
    }


    //登录逻辑
    @PostMapping("/login")
    public Result login(@RequestBody LoginFrom loginFrom,
                        HttpServletRequest request){
        //验证码校验
        HttpSession session = request.getSession();
        String sessionVerCode = (String) session.getAttribute("verifiCode");
        String loginVerCode = loginFrom.getVerifiCode();

        if ("".equals(sessionVerCode) || null == sessionVerCode){
            return Result.fail().message("验证码失效,请少受重试!");
        }
        if (!sessionVerCode.equalsIgnoreCase(loginVerCode)){
            return Result.fail().message("验证码有误,请小心输入!");
        }
        //从 session中移除先用的验证码
        session.removeAttribute("verifiCode");

        //创建map 为返回的token做准备
        Map<String,Object> map = new LinkedHashMap<>();

        //分用户类型 来进行判断
        switch (loginFrom.getUserType()){
            case 1:
                try{
                    Admin admin = adminService.login(loginFrom);
                    if (null != admin){
                        // 找到该用户 给该用户生成token
                        map.put("token",JwtHelper.createToken(admin.getId().longValue(),1));
                    }else {
                        throw new RuntimeException("用户名或者密码有误!");
                    }
                    return Result.ok(map);
                }catch (RuntimeException e){
                    e.printStackTrace();
                    return Result.fail().message(e.getMessage());
                }
        }

        return Result.fail().message("没用该用户信息");
    }





    //sms/system/getVerifiCodeImage
    //获取验证码 图片
    @RequestMapping("/getVerifiCodeImage")
    public void getVerifiCodeImage(
            HttpServletRequest request,
            HttpServletResponse response
    ){
        //获取图片
        BufferedImage verifiCodeImage = CreateVerifiCodeImage.getVerifiCodeImage();
        //获取图片的验证码
        String verifiCode = new String(CreateVerifiCodeImage.getVerifiCode());

        //将验证码文本放入session中 存入到为下次验证做准备
        HttpSession session = request.getSession();
        session.setAttribute("verifiCode",verifiCode);

        //将验证码图片 响应给浏览器
        try {
            ImageIO.write(verifiCodeImage,"JPEG",response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
